package team.tttxs.ct.hibernate.dao.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

/**
 * if isRangeSupported is true, then "offset" and "page number" are not used when query
 *
 */
public class Page {
	
	private int pagenumber = 1;
	
	private int pagesize = 20;
	
	private int offset = 0;
	
	private List<RangeCriteria> rangeCriteria;
	
	private Map<String, Integer> orderClauses = new LinkedHashMap<String, Integer>();
	
	public Page() {
		//default
	}
	
	public Page(int pagenumber, int pagesize) {
		this.pagenumber = pagenumber ;
		this.pagesize = pagesize ;
		this.offset = (pagenumber-1) * pagesize ;
	}

	public int getPagenumber() {
		return pagenumber;
	}

	public int getPagesize() {
		return pagesize;
	}

	public int getOffset() {
		return offset;
	}
	
	public void addOrderClauses(String column, Integer orderCode) {
		//Order order = (orderCode <=0 || orderCode == null) ? Order.DESCENDING : Order.ASCENDING;
		this.orderClauses.put(column, orderCode);
	}

	public Map<String, Integer> getOrderClauses() {
		return orderClauses;
	}

	public void setOrderClauses(Map<String, Integer> orderClauses) {
		this.orderClauses = orderClauses;
	}
	
	public void setOrderClauses(String str) {
		if(StringUtils.hasText(str)) {
			for(String token : str.split(",")) {
				String lastChar = token.substring(token.length()-1, token.length());
				if(lastChar.equals("+")) {
					this.addOrderClauses(token.substring(0, token.length() - 1), 1);
				} else if(lastChar.equals("-")) {
					this.addOrderClauses(token.substring(0, token.length() - 1), 0);
				} else {
					this.addOrderClauses(token.substring(0, token.length()), 0);
				}
			}
		}
	}
	
	public List<RangeCriteria> getRangeCriteria() {
		return rangeCriteria;
	}

	public void setRangeCriteria(List<RangeCriteria> rangeCriteria) {
		this.rangeCriteria = rangeCriteria;
	}

	public void addRangeCrit(RangeCriteria rangeCrit) {
		if(rangeCriteria == null) {
			rangeCriteria = new ArrayList<RangeCriteria>();
		}
		rangeCriteria.add(rangeCrit);
	}

	public void setPagenumber(int pagenumber) {
		this.pagenumber = pagenumber;
		this.offset = (pagenumber-1) * pagesize ;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public boolean isSortable() {
		return orderClauses.size() > 0 ;
	}
	
	public boolean isRangeSupported() {
		return rangeCriteria != null && rangeCriteria.size() > 0;
	}
}
